package com.kingzoon.seckill.service.impl.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kingzoon.seckill.dao.Oauth2UserMapper;
import com.kingzoon.seckill.entity.Oauth2User;
import com.kingzoon.seckill.entity.Oauth2UserExample;
import com.kingzoon.seckill.service.UserService;

import java.util.List;

@Transactional
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private Oauth2UserMapper userDao;
	@Autowired
	private PasswordHelper passwordHelper;

	private Oauth2UserExample oauth2UserExample = new Oauth2UserExample();

	/**
	 * 创建用户
	 * @param user
	 */
	public Oauth2User createUser(Oauth2User user) {
		//加密密码
		passwordHelper.encryptPassword(user);
		int a = userDao.insertSelective(user);
		if (a != 1) {
			return null;
		}
		oauth2UserExample.createCriteria().andIdEqualTo(user.getId());
		List<Oauth2User> list = userDao.selectByExample(oauth2UserExample);
		if (list == null || list.size() <= 0) {
			return null;
		}
		user = list.get(0);
		return user;
	}

	public Oauth2User updateUser(Oauth2User user) {
		int a = userDao.updateByPrimaryKeySelective(user);
		if (a != 1) {
			return null;
		}

		oauth2UserExample.createCriteria().andIdEqualTo(user.getId());
		List<Oauth2User> list = userDao.selectByExample(oauth2UserExample);
		if (list == null || list.size() <= 0) {
			return null;
		}
		user = list.get(0);
		return user;
	}

	public void deleteUser(Long userId) {
		userDao.deleteByPrimaryKey(userId);
	}

	/**
	 * 修改密码
	 * @param userId
	 * @param newPassword
	 */
	public void changePassword(Long userId, String newPassword) {
		Oauth2User user = userDao.selectByPrimaryKey(userId);
		user.setPassword(newPassword);
		passwordHelper.encryptPassword(user);
		userDao.updateByPrimaryKeySelective(user);
	}

	public Oauth2User findOne(Long userId) {
		return userDao.selectByPrimaryKey(userId);
	}

	public List<Oauth2User> findAll() {
		return userDao.selectByExample(oauth2UserExample);
	}

	/**
	 * 根据用户名查找用户
	 * @param username
	 * @return
	 */
	public Oauth2User findByUsername(String username) {
		oauth2UserExample.createCriteria().andUsernameEqualTo(username);
		List<Oauth2User> list = userDao.selectByExample(oauth2UserExample);
		Oauth2User oauth2User = list.get(0);
		return oauth2User;
	}

}
